<template>

    <div>
        <el-form :inline="true" :model="query" class="query-form" size="mini">
            <el-form-item class="query-form-item" label="区服">
                <el-select v-model="query.server" placeholder="请选择" clearable>
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item class="query-form-item" label="支付状态">
                <el-select v-model="query.paymentStatus" placeholder="请选择" clearable>
                    <el-option label="未支付" :value="0"></el-option>
                    <el-option label="已支付" :value="1"></el-option>
                    <el-option label="取消支付" :value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item class="query-form-item" label="订单状态">
                <el-select v-model="query.status" placeholder="请选择" clearable>
                    <el-option label="未接单" :value="0"></el-option>
                    <el-option label="订单完成" :value="1"></el-option>
                    <el-option label="订单取消" :value="2"></el-option>
                    <el-option label="已接单" :value="3"></el-option>
                    <el-option label="已删除" :value="4"></el-option>
                    <el-option label="已发货" :value="5"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item class="query-form-item" label="下单日期">
                <el-date-picker
                    v-model="query.orderTime"
                    type="datetimerange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00', '23:59:59']"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button-group>
                    <el-button type="primary" icon="el-icon-refresh" @click="onReset"></el-button>
                    <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
                </el-button-group>
            </el-form-item>
        </el-form>
        <el-table
            v-loading="loading"
            :data="list"
            style="width: 100%;">
            <el-table-column
                label="订单号"
                prop="id" width="200"
                fixed>
            </el-table-column>
            <el-table-column
                label="订单状态"
                prop="status"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{statusMap[scope.row.status]}}
                </template>
            </el-table-column>
            <el-table-column
                label="支付方式"
                prop="paymentMethod"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{scope.row.paymentMethod == '0' ? '支付宝' : scope.row.paymentMethod == '1' ? '微信':'其他'}}
                </template>
            </el-table-column>
            <el-table-column
                label="支付状态"
                prop="paymentStatus"
                with="300"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{scope.row.paymentStatus == '1' ? '已支付' : '未支付'}}
                </template>
            </el-table-column>
            <el-table-column
                label="商品信息"
                prop="amount"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{scope.row.itemDesc}}
                </template>
            </el-table-column>
            <el-table-column
                label="订单数量(万金)"
                prop="price"
                width="150"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{(scope.row.totalAmount).toFixed(2) * scope.row.rate}}
                </template>
            </el-table-column>

            <el-table-column
                label="总金额(元)"
                prop="price"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{(scope.row.totalAmount).toFixed(2)}}
                </template>
            </el-table-column>
            <el-table-column
                label="游戏区服"
                prop="gameServer"
                :show-overflow-tooltip="true"
                fixed>
            </el-table-column>
            <el-table-column
                label="收货角色"
                prop="gameUserName"
                :show-overflow-tooltip="true"
                fixed>
            </el-table-column>
            <el-table-column
                label="会员账号"
                prop="userName"
                :show-overflow-tooltip="true"
                fixed>
            </el-table-column>
            <el-table-column
                label="交易服务端"
                prop="phone"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{'公众号'}}
                </template>
            </el-table-column>


            <el-table-column
                label="下单时间"
                width="150"
                prop="createTime"
                :show-overflow-tooltip="true"
                fixed>
            </el-table-column>
            <el-table-column
                label="完成时间"
                prop="userId"
                :show-overflow-tooltip="true"
                fixed>
                <template slot-scope="scope">
                    {{scope.row.status == 1 ? scope.row.updateTime : ''}}
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                width="150px"
                fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" size="small"
                               @click.native="gotoDetail( scope.row)">详情</el-button>
                    <el-divider direction="vertical"></el-divider>

                    <el-badge :value="scope.row.unreadCount"
                              :hidden="scope.row.unreadCount == 0"
                              class="item">
                        <el-button type="text" size="small"
                                   @click.native="gotoChat( scope.row)">进入聊天</el-button>
                    </el-badge>
<!--                    <el-button type="text" size="small"-->
<!--                               @click.native="gotoChat( scope.row)">进入聊天</el-button>-->
                    <!--                    <el-button type="text" size="small"-->
                    <!--                               @click.native="handleDel(scope.$index, scope.row)">详情</el-button>-->
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            :page-size="query.limit"
            @current-change="handleCurrentChange"
            layout="prev, pager, next"
            :total="total">
        </el-pagination>

        <!--表单-->
        <el-dialog
            :title="formMap[formName]"
            :visible.sync="formVisible"
            :before-close="hideForm"
            width="450px"
            top="5vh">
            <el-form label-position="left" label-width="80px" :model="formData" :rules="formRules" ref="dataForm">

                <el-form-item label="游戏区服" prop="gameServer">
                    <!--                    <el-input v-model="formData.gameServer" auto-complete="off"></el-input>-->
                    <el-select v-model="formData.gameServer" placeholder="请选择游戏区服">
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量" prop="amount">
                    <el-input v-model="formData.amount" auto-complete="off">
                        <template slot="append">个</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="销售价" prop="price">
                    <el-input v-model="formData.price" auto-complete="off">
                        <template slot="append">个/元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="交易方式" prop="auction">
                    <el-select v-model="formData.auction" placeholder="请选择拍卖方式">
                        <el-option
                            :key="'邮寄'"
                            :label="'邮寄'"
                            :value="'邮寄'">
                        </el-option>
                        <el-option
                            :key="'拍卖'"
                            :label="'拍卖'"
                            :value="'拍卖'">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="手续费" prop="charge">
                    <el-input v-model="formData.charge" auto-complete="off">
                        <template slot="append">%</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" type="textarea"  show-word-limit maxlength="200" auto-complete="off" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="hideForm">取消</el-button>
                <el-button type="primary" @click.native="formSubmit()" :loading="formLoading">提交</el-button>
            </div>
        </el-dialog>


        <el-dialog
            title="订单对话"
            :visible.sync="chatDialog"
            width="90%" destroy-on-close
            :before-close="()=>{
                chatDialog = false
            }">
            <order-chat v-if="chatDialog" :order-id="selectRow.id" :order-data="selectRow"></order-chat>
            <span slot="footer" class="dialog-footer">
                <el-button @click="()=>{
                    chatDialog = false
                }">关 闭</el-button>
              </span>
        </el-dialog>

        <el-drawer
            title="订单详情"
            :visible.sync="drawer"
            :direction="'rtl'"
            size="1200px"
            :before-close="()=>{
                drawer=false
            }">

            <div style="margin: 20px">
                <div  style="margin: auto 200px">
                    <el-steps :active="selectRow.status == 1 ? 5 : (selectRow.status == 5 ? 3 : (selectRow.status == 3 ? 2 : selectRow.paymentStatus == 1 ? 2 : 1))">
                        <el-step title="订单已生成" :description="selectRow.createTime"></el-step>
                        <el-step title="买家已付款" description=""></el-step>
                        <el-step title="等待发货" description=""></el-step>
                        <el-step title="等待完成" description=""></el-step>
                    </el-steps>
                </div>
                <el-descriptions title="" style="margin-top: 10px"  :column="1" border>
                    <el-descriptions-item label-class-name="my-label" label="订单号">{{selectRow.id}}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="商品信息"  style="margin-top: 10px"  :column="1" border>
                    <el-descriptions-item label-class-name="my-label" label="商品名称">{{selectRow.itemDesc}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="销售价">{{selectRow.totalAmount}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="优惠价" >{{selectRow.totalAmount}}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="收货信息"  style="margin-top: 10px"  :column="1" border>
                    <el-descriptions-item label-class-name="my-label" label="收货用户名">{{selectRow.gameUserName}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="收货区服">{{selectRow.gameServer}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="手机号">{{selectRow.userName}}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="支付配送"  style="margin-top: 10px"  :column="1" border>
                    <el-descriptions-item label-class-name="my-label" label="支付方式"> {{selectRow.paymentMethod == '0' ? '支付宝' : selectRow.paymentMethod == '1' ? '微信':'其他'}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="配送方式">{{selectRow.auction}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="发货平台" >{{selectRow.platform}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="订单备注">{{selectRow.notes}}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="订单统计"  style="margin-top: 10px"  :column="1" border>
                    <el-descriptions-item label-class-name="my-label" label="订单总金额">{{selectRow.totalAmount + '元'}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="订购数量">{{ ((selectRow.totalAmount || 0).toFixed(2) * selectRow.rate) + '万金'}}</el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label" label="实发数量" >{{ ((selectRow.totalAmount || 0).toFixed(2) * selectRow.rate)  + '万金'}}</el-descriptions-item>
                </el-descriptions>

                <el-button-group style="margin-top: 20px">

                    <el-button type="primary" v-for="(item, index) in btns" :key="index" @click="orderOption(item.name)" >{{item.title}}</el-button>
                </el-button-group>
            </div>
        </el-drawer>
    </div>

</template>

<script>
import { list, save, del} from "../../api/dnf/order";
import Upload from "../../components/File/Upload.vue";
import OrderChat from "./OrderChat.vue";
import axios from "@/utils/axios";
import {parseTime} from "@/filtres";
const formJson = {
    id: "",
    auction: "",
    gameServer: "",
    price: "",
    charge: "",
    amount: "",
    type: "1,2,4,11,13",
    remark: "",
    platform: "自营"
};
export default {
    data() {
        return {
            drawer: false,
            statusMap:{
                '0': '未发货',
                '1': '订单完成',
                '2': '订单取消',
                '3': '卖家已接单',
                '4': '订单删除',
                '5': '卖家已发货'
            },
            selectRow: {},
            chatDialog: false,
            options: [
                {//跨1,跨2,跨3A,跨3B,跨4,跨5,跨6,跨7/8
                    value: '跨1',
                    label: '跨1'
                },
                {
                    value: '跨2',
                    label: '跨2'
                },
                {
                    value: '跨3A',
                    label: '跨3A'
                },
                {
                    value: '跨3B',
                    label: '跨3B'
                },
                {
                    value: '跨4',
                    label: '跨4'
                },
                {
                    value: '跨5',
                    label: '跨5'
                },
                {
                    value: '跨6',
                    label: '跨6'
                },
                {
                    value: '跨7/8',
                    label: '跨7/8'
                }
            ],
            query: {
                orderTime: [
                    parseTime(new Date(),'{y}-{m}-{d} 00:00:00'),
                    parseTime(new Date(),'{y}-{m}-{d} 23:59:59')
                ],
                page: 1,
                limit: 10
            },
            channelListInput: "",
            androidVersionListInput: "",
            iosVersionListInput: "",
            list: [],
            total: 0,
            loading: true,
            index: null,
            formName: null,
            formMap: {
                add: "新增",
                edit: "编辑"
            },
            formLoading: false,
            formVisible: false,
            formData: formJson,
            formRules: {
                auction: [
                    {
                        required: true,
                        message: "请输入拍卖方式",
                        trigger: "blur"
                    }
                ],
                gameServer: [
                    {
                        required: true,
                        message: "请输入游戏区服",
                        trigger: "blur"
                    }
                ],
                price: [
                    {
                        required: true,
                        message: "请输入销售价",
                        trigger: "blur"
                    }
                ],
                charge: [
                    {
                        required: true,
                        message: "请输入手续费",
                        trigger: "blur"
                    }
                ],
                amount: [
                    {
                        required: true,
                        message: "请输入数量",
                        trigger: "blur"
                    }
                ],
                platform: [
                    {
                        required: true,
                        message: "请输入平台",
                        trigger: "blur"
                    }
                ],
            },
            deleteLoading: false
        };
    },
    computed:{
        btns(){
            if (this.selectRow.paymentStatus != '1'){
                return [];
            }
            if (this.selectRow.status == 2){
                return [];
            }
            let isBuy = [4,12,14].includes(this.selectRow.type)  ;
            let arr = []
            switch (this.selectRow.status) {
                case 0:
                    if (isBuy){
                        arr = []
                    }else{
                        arr = [
                            { name: 'take', title: '商家接单' },
                            { name: 'send', title: '订单发货' },
                        ]
                    }
                    break;

                case 3:
                    if (isBuy){
                        arr = []
                    }else{
                        arr = [
                            { name: 'send', title: '订单发货' },
                        ]

                    }
                    break;
                case 5:
                    if (isBuy){
                        arr = [
                            { name: 'receive', title: '确认收货' }
                        ]
                    }else{
                        arr = [
                        ]
                    }
                    break;
                case 4:
                case 2:
                case 1:
                    arr = [
                    ]
                    break;
                // { name: 'detail', title: '订单详情' },
                // { name: 'take', title: '商家接单' },
                // { name: 'send', title: '订单发货' },
                // { name: 'receive', title: '确认收货' },
            }
            if (this.selectRow.status != 1){
                arr.push({name: 'cancel', title: '取消订单'})
            }
            return arr;
        }
    },
    components: {
        Upload,
        OrderChat
    },
    methods: {
        onReset() {
            this.$router.push({
                path: ""
            });
            this.query = {
                title: "",
                page: 1,
                limit: 10
            };
            this.getList();
        },
        onSubmit() {
            this.$router.push({
                path: "",
                query: this.query
            });
            sessionStorage.setItem("order3.query", JSON.stringify(this.query))

            this.getList();
        },
        handleSizeChange(val) {
            this.query.limit = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.query.page = val;
            this.getList();
        },
        getList() {
            this.loading = true;
            list({
                ...this.query,
                type: "2"
            })
                .then(response => {
                    this.loading = false;
                    this.list = response.data.records || [];
                    this.total = response.data.total || 0;
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.total = 0;
                });
        },
        // 删除渠道
        handleChannelListClose(index) {
            console.log(index);
            // 更改值
            this.formData.channelList.splice(index, 1);
        },
        cancelOrder(orderId){
            this.$confirm("确认取消订单吗?", "提示", {
                type: "warning"
            })
                .then(() => {
                    axios({
                        url: "/admin/dnf/order/cancel",
                        method: "post",
                        data: {
                            id: orderId,
                        }
                    }).then(res=>{
                        if (res.code == 1){
                            this.$message.error(res.message)
                            return
                        }

                        this.selectRow.status = 2;
                        this.$message.success("取消成功")
                    })
                });
        },
        completedOrder(orderId){
            axios({
                url: "/admin/dnf/order/completed",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                    return
                }

                this.selectRow.status = 1;
                this.$message.success("操作成功")
            })

        },
        orderDetail(id){
            this.showDetail = true;
            axios({
                url: "/admin/dnf/order/"+id,
                method: "get",
            }).then(res=>{
                console.log("===========>",res)
                this.formData = {...res.data};
                this.showDetail = true
                if ([4,12,14].includes(this.formData.type) && this.formData.status == 0){
                    this.takeOrder(this.formData.id )
                }
            })
        },
        receive(orderId){
            axios({
                url: "/admin/dnf/order/confirmReceive",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                    return
                }

                this.selectRow.status = 1;
                this.$message.success("操作成功")
            })
        },
        sendOrder(orderId){
            axios({
                url: "/admin/dnf/order/send",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                    return
                }

                this.selectRow.status = 5;
                this.$message.success("操作成功")
            })
        },
        takeOrder(orderId){
            axios({
                url: "/admin/dnf/order/take",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                    return
                }
                this.selectRow.status = 3;
                this.$message.success("操作成功")
                // let obj = {
                //     sender_id: '客服',
                //     groupId: this.orderId,
                //     from: '客服',
                //     createTime: new Date().getTime(),
                //     cmd: 11,
                //     chatType: "1",
                //     msgType: "0",
                //     content: "商家已接单"
                // }
                // this.socket.send(JSON.stringify(obj));
            })
        },
        orderOption(action){
            switch (action) {
                case 'take':
                    this.takeOrder(this.selectRow.id);
                    return
                case 'completed':
                    this.completedOrder(this.selectRow.id);
                    return
                case 'cancel':
                    this.cancelOrder(this.selectRow.id);
                    return
                case 'send':
                    this.sendOrder(this.selectRow.id);
                    return
                case 'receive':
                    this.receive(this.selectRow.id);
                    return
                case 'detail':
                    this.orderDetail(this.selectRow.id);
                    return
            }
        },
        // 添加渠道白名单
        handleChannelListSubmit() {
            // 更改值
            if (
                this.channelListInput &&
                this.formData.channelList.length < 15
            ) {
                let arr = this.channelListInput.split(",");
                for (let i in arr) {
                    if (
                        arr[i] !== "" &&
                        (this.formData.channelList.length === 0 ||
                            this.formData.channelList.indexOf(arr[i]) < 0)
                    ) {
                        this.formData.channelList.push(arr[i]);
                    }
                }
                this.channelListInput = "";
                this.$refs.channelListRef.focus();
            }
        },
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空字段
                this.$refs["dataForm"].resetFields();
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
            }
        },
        // 隐藏表单
        hideForm() {
            // 更改值
            this.formVisible = !this.formVisible;
            return true;
        },
        gotoDetail(row){
            this.selectRow = row;
            this.drawer = true
        },
        gotoChat(row){
            this.selectRow = row;
            this.chatDialog = true
        },
        // 显示表单
        handleForm(index, row) {
            this.formVisible = true;
            // 刷新表单
            this.resetForm();
            this.formData = JSON.parse(JSON.stringify(formJson));
            if (row !== null) {
                this.formData = Object.assign({}, row);
            }
            this.formName = "add";
            if (index !== null) {
                this.index = index;
                this.formName = "edit";
            }
        },
        formSubmit() {
            this.$refs["dataForm"].validate(valid => {
                if (valid) {
                    this.formLoading = true;
                    let data = Object.assign({}, this.formData);
                    save(data, this.formName)
                        .then(response => {
                            this.formLoading = false;
                            if (response.code) {
                                this.$message.error(response.message);
                                return false;
                            }
                            this.$message.success("操作成功");
                            this.formVisible = false;
                            this.getList();
                            // if (this.formName === "add") {
                            //     // 向头部添加数据
                            //     data.adId = response.data.adId;
                            //     this.list.unshift(data);
                            // } else {
                            //     this.list.splice(this.index, 1, data);
                            // }
                        })
                        .catch(() => {
                            this.formLoading = false;
                        });
                }
            });
        },
        // 删除
        handleDel(index, row) {
            if (row.id) {
                this.$confirm("确认删除该记录吗?", "提示", {
                    type: "warning"
                })
                    .then(() => {
                        let para = { id: row.id };
                        this.deleteLoading = true;
                        del(para)
                            .then(response => {
                                this.deleteLoading = false;
                                if (response.code) {
                                    this.$message.error(response.message);
                                    return false;
                                }
                                this.$message("删除成功");
                                // 刷新数据
                                this.list.splice(index, 1);
                            })
                            .catch(() => {
                                this.deleteLoading = false;
                            });
                    })
                    .catch(() => {
                        this.$message.info("取消删除");
                    });
            }
        },
        onSelectPic(filePath, filePathUrl) {
            this.formData.pic = filePath;
            this.formData.picUrl = filePathUrl;
        }
    },
    filters: {
        statusFilterType(status) {
            const statusMap = {
                0: "gray",
                1: "success"
            };
            return statusMap[status];
        },
        statusFilterName(status) {
            const statusMap = {
                0: "禁用",
                1: "正常"
            };
            return statusMap[status];
        }
    },
    mounted() {},
    created() {
        // 将参数拷贝进查询对象
        let query = JSON.parse(  sessionStorage.getItem("order3.query"));
        this.query = Object.assign(this.query, query);
        this.query.limit = parseInt(this.query.limit);
        // 加载表格数据
        this.getList();
    }
};
</script>

<style type="text/scss" lang="scss">
.my-label{
    width: 20%;
}
</style>

<style  lang="scss" scoped>
/deep/ .el-table_1_column_14 .cell{
    overflow: visible !important;
}
</style>
